<?php

namespace Biz\service\brand;

use Biz\cache\brand\Brand as cBrand;
use Biz\cache\brand\BrandAliasCache;
use Biz\cache\brand\BrandResumeInfo;
use Biz\model\brand\Brand as mBrand;
use Biz\model\wiki\Wiki;
use Biz\service\brandAccount\BrandAccount;
use Biz\tools\BizUrl;
use Doraemon\cache\Tag2Brand;
use Doraemon\cache\UserCounter;
use Doraemon\model\admTag;
use Doraemon\model\Category as mCategory;
use Doraemon\model\MemberExtendInfo;
use Doraemon\model\PhotoRelaGoods as mPhotoRelaGoods;
use Doraemon\model\ReleCateBrand as mReleCateBrand;
use Doraemon\model\Spu as mSpu;
use Doraemon\model\Tag as mTag;
use Doraemon\model\UserRelaGoods as mUserRelaGoods;
use Doraemon\service\Member;
use Doraemon\service\Search;
use Doraemon\service\User;
use Doraemon\service\User as sUser;
use Doraemon\tools\HhzClient;
use Doraemon\tools\Hhzurl;
use Doraemon\tools\ImgUrl;
use Doraemon\tools\LinkFormat;
use Hhz\AdministrativeRegion\Region;
use hhz\constant\redis\redisKeys;
use Hhz\Redis\otherRedis;
use Overtrue\Pinyin\Pinyin;

class Brand
{
    const BRAND_DEFAULT_LOGO = 'http://img.hhz1.cn/Op-imageShow/16a88305o05o00000owir9x';

    const BRAND_TYPE = 1;

    const HOT_MODE = 1;//热度
    const TIME_MODE = 2;//时间

    // 品牌是否到期（0：到期；1：未到期）
    const BRAND_ACCOUNT_EXPIRE = 0;
    const BRAND_ACCOUNT_ACTIVE = 1;

    public static function addBrand($data)
    {
        $brandInfo = [
            'brand_name' => $data['brand_name'],
            'en_brand_name' => $data['en_brand_name'],
            'logo' => $data['logo'],
            'discription' => $data['discription'],
            'detail' => $data['detail'],
            'location' => $data['location'],
            'area_code' => $data['area_code'],
            'tag_id' => $data['tag_id'],
            'type' => $data['type'],
            'wiki_status' => $data['wiki_status'],
            'store_status' => $data['store_status'],
            'suggest_status' => $data['suggest_status'],
            'ob_tag' => $data['ob_tag'],
        ];
        $brandId = mBrand::addBrand($brandInfo);
        if ($brandId) {
            self::changeBrandRealCategory($brandId, $data['category_data']);

            Search::updateBrandById($brandId);
            self::updateBrandTag($brandId, $data['tag_id']);
            self::updateBrandTagFile();
        }
        return $brandId;
    }

    public static function filterBrandIdsByWiki($brandIds)
    {
        return mBrand::filterBrandIdsByWiki($brandIds);
    }

    private static function changeBrandRealCategory($brandId, $categoryData)
    {
        $releCates = mReleCateBrand::getBrandAllLink($brandId);
        $allCateIds = array_column($releCates, 'cate_id');
        $newIds = [];
        foreach ($categoryData as $firstId => $rows) {
            if (in_array($firstId, $allCateIds)) {
                mReleCateBrand::update([
                    'cate_deep' => 1,
                    'cate_father_id' => 0,
                    'status' => mReleCateBrand::STATUS_USING,
                    'updated_time' => date("Y-m-d H:i:s"),
                ], ['brand_id' => $brandId, 'cate_id' => $firstId]);
            } else {
                mReleCateBrand::insert([
                    'brand_id' => $brandId,
                    'cate_id' => $firstId,
                    'cate_deep' => 1,
                    'cate_father_id' => 0,
                    'status' => mReleCateBrand::STATUS_USING,
                    'updated_time' => date("Y-m-d H:i:s"),
                    'created_time' => date("Y-m-d H:i:s"),
                ]);
            }
            $newIds[] = (string)$firstId;
            foreach ($rows as $secondId) {
                if (in_array($secondId, $allCateIds)) {
                    mReleCateBrand::update([
                        'cate_deep' => 2,
                        'cate_father_id' => $firstId,
                        'status' => mReleCateBrand::STATUS_USING,
                        'updated_time' => date("Y-m-d H:i:s"),
                    ], ['brand_id' => $brandId, 'cate_id' => $secondId]);
                } else {
                    mReleCateBrand::insert([
                        'brand_id' => $brandId,
                        'cate_id' => $secondId,
                        'cate_deep' => 2,
                        'cate_father_id' => $firstId,
                        'status' => mReleCateBrand::STATUS_USING,
                        'updated_time' => date("Y-m-d H:i:s"),
                        'created_time' => date("Y-m-d H:i:s"),
                    ]);
                }
                $newIds[] = (string)$secondId;
            }
        }
        $delCateIds = array_diff($allCateIds, $newIds);
        foreach ($delCateIds as $cateId) {
            mReleCateBrand::update([
                'status' => mReleCateBrand::STATUS_DELETE,
                'updated_time' => date("Y-m-d H:i:s"),
            ], ['brand_id' => $brandId, 'cate_id' => $cateId]);
        }
    }

    public static function updateBrandInfoById($brandId, $data)
    {
        $oriBrandInfo = mBrand::getBrandInfoById($brandId);
        $brandInfo = [
            'brand_name' => $data['brand_name'],
            'en_brand_name' => $data['en_brand_name'],
            'logo' => $data['logo'],
            'discription' => $data['discription'],
            'detail' => $data['detail'],
            'location' => $data['location'],
            'area_code' => $data['area_code'],
            'tag_id' => $data['tag_id'],
            'type' => $data['type'],
            'wiki_status' => $data['wiki_status'],
            'store_status' => $data['store_status'],
            'suggest_status' => $data['suggest_status'],
            'ob_tag' => $data['ob_tag'],
        ];
        mBrand::updateBrandInfoById($brandId, $brandInfo);
        self::changeBrandRealCategory($brandId, $data['category_data']);

        if ($oriBrandInfo['suggest_status'] != $data['suggest_status']) {
            if ($data['suggest_status'] == mBrand::SUGGEST_STATUS_NOT) {
                mSpu::update(['suggest_status' => mSpu::SUGGEST_STATUS_NOT], [
                    'brand_id' => $brandId,
                    'suggest_sign' => mSpu::SUGGEST_STATUS_NORMAL
                ]);
            } else {
                $suggestCategoryIds = mCategory::getCategoryIdsBySuggestStatus(mCategory::SUGGEST_STATUS_NORMAL);
                mSpu::update([
                    'suggest_status' => mSpu::SUGGEST_STATUS_ABLE,
                    'suggest_time' => date('Y-m-d H:i:s')
                ], [
                    'brand_id' => $brandId,
                    'suggest_sign' => mSpu::SUGGEST_STATUS_NORMAL,
                    'category_id' => $suggestCategoryIds
                ]);
            }
        }
        if ($oriBrandInfo['wiki_status'] != $data['wiki_status'] && $data['wiki_status'] == mBrand::WIKI_STATUS_VISIBLE) {
            mSpu::update(['shelves_time' => date("Y-m-d H:i:s")], [
                'brand_id' => $brandId,
                'status' => mSpu::STATUS_REVIEW
            ]);
        }
        Search::updateBrandById($brandId);
        self::updateBrandTag($brandId, $data['tag_id']);
        return $brandId;
    }

    public static function updateBrandTag($brandId, $tagId)
    {
        if ($tagId) {
            $tagName = mTag::getTagNameById($tagId);
        } else {
            $tagName = null;
        }
        Tag2Brand::setBrandTag($brandId, $tagName[0]);
    }

    public static function updateBrandTagFile()
    {
        $brandList = mBrand::getAllBrand();
        $tagIds = array_column($brandList, 'tag_id');
        $tagList = mTag::getTagsByIds($tagIds);
        $tags = [];
        foreach ($tagList as $tag) {
            $tags[$tag['id']] = $tag['tag'];
        }
        $formatData = [];
        foreach ($brandList as $brand) {
            if (isset($tags[$brand['tag_id']])) {
                $formatData[] = [
                    'brand_id' => $brand['id'],
                    'brand_name' => $brand['brand_name'],
                    'tag_name' => $tags[$brand['tag_id']]
                ];
            }
        }
        file_put_contents('/home/adm_rsync_dir/tags/adm_link_to_brand.json', json_encode($formatData));
    }

    public static function getBrandsIdsByStoreStatus($storeStatus)
    {
        return mBrand::getBrandIdsByStoreStatus($storeStatus);
    }

    /**
     * (已废弃)
     *
     * @param array $where
     * @param array $order
     * @param array $limit
     * @return array
     * @deprecated
     */
    public static function getBrand($where = [], $order = [], $limit = [])
    {
        $result = [
            'list' => [],
            'count' => 0
        ];
        if ($where['brandName']) {
            $brandWhere = [
                'brandName' => $where['brandName'],
                'brandIds' => []
            ];
        } else {
            $brandWhere = ['brandIds' => []];
        }
        if ($where['uid']) {
            $brandWhere = ['uid' => $where['uid']];
        }
        if ($where['id']) {
            $id = $where['id'];
            $brandWhere = ['brandIds' => [$id]];
        }
        if (strlen($where['type'])) {
            $brandWhere['type'] = $where['type'];
        }
        if (strlen($where['brand_type'])) {
            $brandWhere['brand_type'] = $where['brand_type'];
        }
        if (strlen($where['wikiStatus'])) {
            $brandWhere['wikiStatus'] = $where['wikiStatus'];
        }
        if (isset($where['storeStatus']) && strlen($where['storeStatus'])) {
            $brandWhere['storeStatus'] = $where['storeStatus'];
        }
        if (strlen($where['suggestStatus'])) {
            $brandWhere['suggestStatus'] = $where['suggestStatus'];
        }
        //如果指定类目
        if (isset($where['categoryIds'])) {
            $brandIds = mReleCateBrand::getBrandIdByCategoryIds($where['categoryIds']);
            if ($brandIds) {
                $brandWhere['brandIds'] = $brandWhere['brandIds'] ? array_intersect($brandWhere['brandIds'],
                    $brandIds) : $brandIds;
            } else {
                return $result;
            }
        }
        //如果指定已包含商品
        if (isset($where['hasSpu']) && $where['hasSpu']) {
            $brandIds = mSpu::getHasSpuBrandIds();
            if ($brandIds) {
                $brandWhere['brandIds'] = $brandWhere['brandIds'] ? array_intersect($brandWhere['brandIds'],
                    $brandIds) : $brandIds;
                if (empty($brandWhere['brandIds'])) {
                    return $result;
                }
            } else {
                return $result;
            }
        }
        //如果指定已关联图片
        if (isset($where['hasPhoto']) && $where['hasPhoto']) {
            $brandIds = mPhotoRelaGoods::getHasPhotoBrandIds();
            if ($brandIds) {
                $brandWhere['brandIds'] = $brandWhere['brandIds'] ? array_intersect($brandWhere['brandIds'],
                    $brandIds) : $brandIds;
                if (empty($brandWhere['brandIds'])) {
                    return $result;
                }
            } else {
                return $result;
            }
        }
        $brandList = mBrand::getBrand($brandWhere, $order, $limit);
        $brandInfos = self::formatBrandInfos($brandList);
        return [
            'list' => $brandInfos,
            'count' => mBrand::getBrandCountByWhere($brandWhere)
        ];
    }

    /**
     * （废弃）
     *
     * @param $brandList
     * @return mixed
     * @deprecated
     */
    private static function formatBrandInfos($brandList)
    {
        $brandIds = [];
        foreach ($brandList as &$brand) {
            $areaName = Region::getAreaDetailByCode($brand['area_code']);
            $brand['location'] = $areaName;
            $brand['area_name'] = $areaName;
            $brand['logo'] = $brand['logo'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brand['logo'],
                ImgUrl::IMAGE_SIZE_SQ_PHONE) : ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, '96369302802800000ovjdos',
                ImgUrl::IMAGE_SIZE_SQ_PHONE);
            $brandIds[] = $brand['id'];
        }
        $brandSpuNum = mSpu::getSpuNumGroupByBrand($brandIds);
        $brandSuggestSpuNum = mSpu::getSuggestSpuNumGroupByBrand($brandIds, mSpu::SUGGEST_STATUS_ABLE);
        $brandPrioritySuggestSpuNum = mSpu::getSuggestSpuNumGroupByBrand($brandIds, mSpu::SUGGEST_STATUS_PRIORITY);
        $brandPhotoNum = mPhotoRelaGoods::getPhotoNumGroupByBrand($brandIds);
        $brandRelaNum = mUserRelaGoods::countRelaNumGroupByBrand($brandIds);
        foreach ($brandList as &$brand) {
            $brand['spu_num'] = $brandSpuNum[$brand['id']];
            $brand['suggest_spu_num'] = $brandSuggestSpuNum[$brand['id']];
            $brand['priority_suggest_spu_num'] = $brandPrioritySuggestSpuNum[$brand['id']];
            $brand['photo_num'] = $brandPhotoNum[$brand['id']];
            $brand['fav_num'] = isset($brandRelaNum[$brand['id']]) ? $brandRelaNum[$brand['id']]['fav_num'] : 0;
            $brand['bought_num'] = isset($brandRelaNum[$brand['id']]) ? $brandRelaNum[$brand['id']]['bought_num'] : 0;
            $brand['brand_type_text'] = mBrand::BRAND_TYPE[$brand['brand_type']];
        }
        return $brandList;
    }

    public static function getBrandInfosByUid($uid, $field = '*')
    {
        $brand_info = mBrand::getBrandByFilter(['uid' => $uid], $field);
        return $brand_info;
    }

    public static function deleBrandInfoById($brandId)
    {
        $data['status'] = mReleCateBrand::STATUS_DELETE;
        $data2['status'] = mBrand::STATUS_DELETE;
        mReleCateBrand::updateBrandCateLink($brandId, $data);
        $result = mBrand::updateBrandInfoById($brandId, $data2);
        Search::updateBrandById($brandId);
        return $result;
    }

    public static function getSuperAndExampleUser()
    {
        $payBrandInfos = mBrand::getBrandByFilter([
            "brand_type" => [
                mBrand::BRAND_TYPE_BEST,
                mBrand::BRAND_TYPE_SUPER,
            ]
        ]);

        return $payBrandInfos;
    }

    public static function getBrandInfoById($id)
    {
        $brandInfo = mBrand::getBrandInfoById($id);
        if (!empty($brandInfo)) {
            $areaName = $brandInfo['area_code'] ? Region::getAreaDetailByCode($brandInfo['area_code']) : '';
            $brandInfo['logo_url'] = $brandInfo['logo'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brandInfo['logo'],
                ImgUrl::IMAGE_SIZE_SQ_PHONE) : ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, '96369302802800000ovjdos',
                ImgUrl::IMAGE_SIZE_SQ_PHONE);
            $brandInfo['location'] = $areaName;
            $brandInfo['area_name'] = $areaName;
            $releCates = mReleCateBrand::getCateLinkByBrandId($brandInfo['id']);
            $brandInfo['category_ids'] = array_column($releCates, 'cate_id');
        }
        return $brandInfo;
    }

    /**
     * 获取品牌信息缓存
     *
     * @param array $ids
     * @return array|mixed
     */
    public static function getBrandInfosCache(array $ids)
    {
        [$cacheData, $noCacheKeys] = cBrand::mGetItems($ids);
        if ($noCacheKeys) {
            $mBrandInfos = mBrand::getBrandListByIds($ids);
            cBrand::mSetItems($mBrandInfos);
            $brandInfos = $cacheData + $mBrandInfos;
        } else {
            $brandInfos = $cacheData;
        }
        return $brandInfos;
    }

    /**
     * 获取品牌信息
     *
     * @param array $ids
     * @return array
     */
    public static function getBrandInfoByIds4Goods(array $ids)
    {
        $brandInfos = self::getBrandInfosCache($ids);
        $formatData = [];
        if ($brandInfos) {
            $user_ids = array_unique(array_column($brandInfos, 'uid')) ?: [];
            $user_infos = $user_ids ? sUser::getBatchBasicUserInfo($user_ids) : [];
            $userList = $user_infos ? array_column($user_infos, null, 'uid') : [];
            foreach ($brandInfos as $brandInfo) {
                $userInfo = (isset($userList[$brandInfo['uid']]) && $userList[$brandInfo['uid']]) ? $userList[$brandInfo['uid']] : [];
                $default_logo = $userInfo ? $userInfo['avatar'] : self::BRAND_DEFAULT_LOGO;
                $logo = $brandInfo["logo"] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brandInfo["logo"],
                    ImgUrl::IMAGE_SIZE_SQ_PHONE) : $default_logo;
                $formatData[$brandInfo["id"]] = [
                    "id" => $brandInfo["id"],
                    "name" => $brandInfo["brand_name"],
                    'uid' => $brandInfo['uid'],
                    "nick" => $userInfo ? $userInfo['nick'] : '',
                    "avatar" => $userInfo ? $userInfo['avatar'] : $logo,
                    "logo" => $logo,
                    'brand_type' => $brandInfo["brand_type"],
                    'pack_type' => $brandInfo["pack_type"],
                    'discription' => $brandInfo['discription'],
                ];
            }
        }
        return $formatData;
    }

    public static function getBrandBaseInfoByIds(array $ids)
    {
        $brandInfos = self::getBrandInfosCache($ids);
        $formatData = [];
        if ($brandInfos) {
            foreach ($brandInfos as $brandInfo) {
                $default_logo = self::BRAND_DEFAULT_LOGO;
                $logo = $brandInfo["logo"] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brandInfo["logo"],
                    ImgUrl::IMAGE_SIZE_SQ_PHONE) : $default_logo;
                $formatData[$brandInfo["id"]] = [
                    "id" => $brandInfo["id"],
                    "name" => $brandInfo["brand_name"],
                    'uid' => $brandInfo['uid'],
                    "logo" => $logo,
                    'brand_type' => $brandInfo["brand_type"],
                    'pack_type' => $brandInfo["pack_type"],
                    'discription' => $brandInfo['discription'],
                ];
            }
        }
        return $formatData;
    }

    /** 根据标签id获取品牌logo图
     *
     * @param $tagIds
     * @return array
     */
    public static function getBrandLogoByTagIds($tagIds)
    {
        $result = [];
        if (is_array($tagIds) && $tagIds) {
            $brandInfos = mBrand::getBrandByTagIds($tagIds);
            if (is_array($brandInfos) && $brandInfos) {
                foreach ($brandInfos as $brandInfo) {
                    $brandInfo['logo_url'] = $brandInfo['logo'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ,
                        $brandInfo['logo'], ImgUrl::IMAGE_SIZE_SQ_THUMB) : "";
                    $result[$brandInfo['tag_id']] = $brandInfo['logo_url'];
                }
            }
        }
        return $result;
    }


    /** 根据标签id获取品牌logo图
     *
     * @param $tagIds
     * @return array
     */
    public static function getBrandLogoByTagIds_2($tagIds)
    {
        $result = [];
        if (is_array($tagIds) && $tagIds) {
            $brandInfos = mBrand::getBrandByTagIds_2($tagIds);
            if (is_array($brandInfos) && $brandInfos) {
                foreach ($brandInfos as $brandInfo) {
                    $brandInfo['logo_url'] = $brandInfo['logo'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ,
                        $brandInfo['logo'], ImgUrl::IMAGE_SIZE_SQ_THUMB) : "";
                    $result[$brandInfo['tag_id']] = $brandInfo;
                }
            }
        }
        return $result;
    }

    public static function getBrandsInfoByIds($id)
    {
        return mBrand::getBrandListByIds($id);
    }

    public static function getCateLinkByBrandId($id)
    {
        return mReleCateBrand::getCateLinkByBrandId($id);
    }

    public static function getAllBrand()
    {
        return mBrand::getAllBrand();
    }


    public static function getBrandListByIds4App($ids, $withCount = false)
    {
        $brandInfos = self::getBrandInfosCache($ids);
        $formatData = [];
        if ($brandInfos) {
            foreach ($brandInfos as $brandInfo) {
                $areaName = Region::getAreaDetailByCode($brandInfo['area_code']);
                $formatData[$brandInfo["id"]] = [
                    "id" => $brandInfo["id"],
                    "name" => $brandInfo["brand_name"],
                    "type" => self::BRAND_TYPE,
                    "area" => $areaName,
                    "area_name" => $areaName,
                    "status" => (int)$brandInfo["wiki_status"],
                    "logo" => $brandInfo["logo"] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brandInfo["logo"],
                        ImgUrl::IMAGE_SIZE_SQ_PHONE) : self::BRAND_DEFAULT_LOGO,
                    "thumb_logo" => $brandInfo["logo"] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brandInfo["logo"],
                        ImgUrl::IMAGE_SIZE_SQ_THUMB) : self::BRAND_DEFAULT_LOGO,
                    "logo_status" => (bool)$brandInfo["logo"],
                    "uid" => $brandInfo["uid"],
                    "detail" => trim(implode("\n", [
                        $brandInfo["discription"],
                        $brandInfo["detail"]
                    ])),
                    "url" => $brandInfo["uid"] ? "" : Hhzurl::h5BrandInfo($brandInfo["id"])
                ];
            }
        }
        if ($withCount) {
            $brandSpuNum = mSpu::getSpuNumGroupByBrand($ids, mSpu::STATUS_REVIEW);
            foreach ($formatData as $brandId => $brandInfo) {
                $formatData[$brandId]['count'] = $brandSpuNum[$brandId];
            }
        }
        return $formatData;
    }

    public static function getBrandCommenTagByBIds($brandIds)
    {
        $brandInfos = self::getBrandInfosCache($brandIds);
        $tagIds = array_column($brandInfos, 'tag_id');
        $tagsInfo = admTag::getTagByIds($tagIds);
        $tagsInfo = array_column($tagsInfo, null, 'id');
        $results = [];
        foreach ($brandInfos as $brandId => $brandInfo) {
            if ($brandInfo['tag_id']) {
                $results[$brandId] = isset($tagsInfo[$brandInfo['tag_id']]['common_brand_name']) ? $tagsInfo[$brandInfo['tag_id']]['common_brand_name'] : '';
            } else {
                $results[$brandId] = '';
            }
        }
        return $results;

    }

    public static function getBrandInfo4App($id)
    {
        $brandInfo = mBrand::getBrandInfoById($id);
        $brandSpuNum = mSpu::getSpuNumGroupByBrand([$id], mSpu::STATUS_REVIEW);
        $areaName = Region::getAreaDetailByCode($brandInfo['area_code']);
        $formatData = [
            "id" => $brandInfo["id"],
            "name" => $brandInfo["brand_name"],
            "type" => self::BRAND_TYPE,
            "area" => $areaName,
            "area_name" => $areaName,
            "status" => (int)$brandInfo["wiki_status"],
            "logo" => $brandInfo["logo"] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brandInfo["logo"],
                ImgUrl::IMAGE_SIZE_SQ_THUMB) : self::BRAND_DEFAULT_LOGO,
            "uid" => $brandInfo["uid"],
            "count" => $brandSpuNum[$brandInfo["id"]],
            "detail" => trim(implode("\n", [
                $brandInfo["discription"],
                $brandInfo["detail"]
            ]))
        ];
        return $formatData;
    }

    public static function mgtGetSuggestByBrandName($brandName, $uid = 0)
    {

        $uid = mBrand::get('uid', ['uid' => $uid, 'status' => mBrand::STATUS_USING]);

        if ($uid) {
            $where['AND']['uid'] = $uid;
        }
        $where['AND']['status'] = mBrand::STATUS_USING;
        $where['OR'] = [
            'brand_name[~]' => $brandName,
            'en_brand_name[~]' => $brandName,
        ];

        $suggest = mBrand::select(['id', 'brand_name', 'uid'], $where);

        return $suggest;
    }


    /**
     * 点图标签 brand info
     *
     * @param $note_pic_tag_list
     * @return mixed
     */
    public function handelBrandTag($note_pic_tag_list)
    {
        try {
            $img_tags = array_column($note_pic_tag_list, 'img_tags') ?: [];
            if ($img_tags && is_array($img_tags)) {
                $hash_brand_info = self::getBrandInfoByImgTags($img_tags);
            }
            foreach ($note_pic_tag_list as &$note_pic_tag) {
                $img_tags = array_map(function (&$img_tag) use ($hash_brand_info) {
                    if (($img_tag['type'] == 2 || $img_tag['type'] == 3)) {
                        $brand_name = $img_tag['brand'] ?: $img_tag['user_tag'];
                        if ($hash_brand_info[$brand_name]) {
                            $img_tag['brand_type'] = $hash_brand_info[$brand_name]['brand_type'];
                            $img_tag['uid'] = $hash_brand_info[$brand_name]['uid'];
                            $img_tag['logo_url'] = $hash_brand_info[$brand_name]['logo'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ,
                                $hash_brand_info[$brand_name]['logo'], ImgUrl::IMAGE_SIZE_SQ_THUMB) : "";
                            $img_tag['brand_id'] = $hash_brand_info[$brand_name]['id'] ?: "";
                            $img_tag['type'] = 3;
                        }
                    }
                    return $img_tag;
                }, $note_pic_tag['img_tags']);

                $note_pic_tag['img_tags'] = array_values($img_tags);

            }
        } catch (\Exception $e) {

        }
        return $note_pic_tag_list;
    }

    /*
     *
     * */
    public static function getAllTags($img_tags)
    {
        if ($img_tags && is_array($img_tags)) {
            $all_tags = [];
            foreach ($img_tags as $tags) {
                $brand_tags = array_column($tags, 'brand') ?: [];
                $user_tags = array_column($tags, 'user_tag') ?: [];
                $all_tags = array_merge($all_tags, $brand_tags, $user_tags);
            }
            $all_tags = array_filter($all_tags);
            if ($all_tags && is_array($all_tags)) {
                foreach ($all_tags as $alias) {
                    $tag = BrandAliasCache::getBrandName($alias) ?: '';
                    if ($tag) {
                        array_push($all_tags, $tag);
                    }
                }
            }
        }
        return $all_tags ?: [];
    }

    /*获取brandInfo
     *
     * */
    public function getBrandInfoByImgTags($img_tags = [])
    {
        $hash_brand_info = [];
        try {
            if ($img_tags && is_array($img_tags)) {
                //alias 转为品牌词
                $tags = self::getAllTags($img_tags);
                $brand_info = [];
                if ($tags && is_array($tags)) {
                    //获取 品牌信息
                    $map = [];
                    $map['brand_name'] = array_unique(array_values($tags));
                    $map['brand_type'] = [mBrand::SUGGEST_STATUS_DOWNGRADE, mBrand::SUGGEST_STATUS_PRIORITY];
                    $brand_info = mBrand::getBrandByFilter($map);
                }
                if ($brand_info && is_array($brand_info)) {
                    foreach ($brand_info as $brand) {
                        $alias_arr = json_decode($brand['brand_alias'], true) ?: [];
                        if ($alias_arr && is_array($alias_arr)) {
                            foreach ($alias_arr as $alias_tag) {
                                $hash_brand_info[$alias_tag] = $brand;
                            }
                        }
                        $hash_brand_info[$brand['brand_name']] = $brand;
                    }
                }
            }
        } catch (\Exception $e) {

        }
        return $hash_brand_info;

    }

    /**
     * 批量 格式化品牌卡片信息
     *
     * @param $brandIds
     * @return array
     */
    public static function multiFormatBrandCard($brandIds)
    {
        $hashFormatData = [];
        $uids = mBrand::getBrandUidsByIds($brandIds);
        $brandInfos = User::getMultiUserInfos($uids);
        $memberExtendInfos = MemberExtendInfo::getInfos($uids);
        if (is_array($brandInfos) && $brandInfos) {
            $resumeInfos = BrandResumeInfo::getResumeInfo($brandIds);
            $resumeInfos = $resumeInfos[0];
            foreach ($brandInfos as $brandInfo) {
                $coverImg = isset($memberExtendInfos[$brandInfo['uid']]) ? $memberExtendInfos[$brandInfo['uid']]['cover_img'] : '';
                $coverImg = $coverImg ? ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $coverImg,
                    ImgUrl::IMAGE_SIZE_ORI_NPHONE) : '';
                $cardImage = isset($brandInfo['brand']['card_image']) ? $brandInfo['brand']['card_image'] : '';//品牌卡片图片-推荐线品牌卡片使用
                $coverImg = $cardImage ? $cardImage : $coverImg;
                if ($coverImg) {
                    $brandInfo['cover_img'] = $coverImg;
                    $brandInfo['counter'] = $brandInfo['count'];
                    unset($brandInfo['count']);
                    $hashFormatData[$brandInfo["brand"]["brand_id"]]['user_info'] = $brandInfo;
                    $resumeInfo = isset($resumeInfos[$brandInfo["brand"]["brand_id"]]) ? $resumeInfos[$brandInfo["brand"]["brand_id"]] : [];
                    $hashFormatData[$brandInfo["brand"]["brand_id"]]['resume_info'] = $resumeInfo;
                }
            }
        }
        return $hashFormatData;
    }

    // maxwell异步执行
    public static function syncFirstLetter($data)
    {
        $pinyin = new Pinyin();
        if ($data['data']['brand_name']) {
            $brandName = $data['data']['brand_name'];
            $firstLetter = mb_substr($brandName, 0, 1);
            if (preg_match("/^[\x{4e00}-\x{9fa5}A-Za-z]+$/u", $firstLetter)) {
                $firstLetter = strtolower($pinyin->abbr($firstLetter));
            }
            BrandAliasCache::setFirstLetter($data['data']['id'], $firstLetter);
        }
    }

    /**
     * @param array $where
     * @param array $order
     * @param array $limit
     * @return array
     */
    public static function getAdBrand(array $where = [], array $order = [], array $limit = []): array
    {
        if ($where['brandName']) {
            $brandWhere = [
                'brandName' => $where['brandName'],
                'brandIds' => []
            ];
        } else {
            $brandWhere = ['brandIds' => []];
        }
        if ($where['uid']) {
            $brandWhere = ['uid' => $where['uid']];
        }
        if ($where['id']) {
            $brandWhere = ['brandIds' => [$where['id']]];
        }
        if (strlen($where['brand_type'])) {
            $brandWhere['brand_type'] = $where['brand_type'];
        }
        if (strlen($where['pack_type'])) {
            $brandWhere['pack_type'] = $where['pack_type'];
        }
        if (strlen($where['is_test'])) {
            $brandWhere['is_test'] = $where['is_test'];
        }
        if (isset($where['status'])) {
            $brandWhere['status'] = $where['status'];
        }
        $brandList = mBrand::getBrand($brandWhere, $order, $limit);
        $brandInfos = self::formatBrandData($brandList);
        return [
            'list' => $brandInfos,
            'count' => mBrand::getBrandCountByWhere($brandWhere)
        ];
    }

    /**
     * 数据处理
     *
     * @param $brandList
     * @return mixed
     */
    private static function formatBrandData($brandList)
    {
        $brandIds = [];
        $uidArr = [];
        foreach ($brandList as &$brand) {
            $areaName = Region::getAreaDetailByCode($brand['area_code']);
            $brand['location'] = $areaName;
            $brand['area_name'] = $areaName;
            $brand['logo'] = $brand['logo'] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brand['logo'],
                ImgUrl::IMAGE_SIZE_SQ_PHONE) : ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, '96369302802800000ovjdos',
                ImgUrl::IMAGE_SIZE_SQ_PHONE);
            $brandIds[] = $brand['id'];
            $uidArr[] = $brand['uid'];
        }

        $brandSpuNum = Wiki::getGroupCountByBrandArr($brandIds);
        $wikiNum = Wiki::getGroupCountByBrandArr($brandIds, true);
        $relateNum = Wiki::getSumByBrandArr($brandIds, 'relate_num');
        $clickBuyNum = Wiki::getSumByBrandArr($brandIds, 'click_buy_num');
        $nickNameArr = $uidArr ? Member::getUserInfoByUserIds($uidArr) : [];


        foreach ($brandList as &$brand) {
            $brand['spu_num'] = $brandSpuNum[$brand['id']] ?? 0; //商品数
            $brand['wiki_num'] = $wikiNum[$brand['id']] ?? 0;//wiki数量
            $brand['relate_num'] = $relateNum[$brand['id']] ?? 0;//关联内容数
            $brand['click_buy_num'] = $clickBuyNum[$brand['id']] ?? 0;//关联内容数
            $brand['nick_name'] = $nickNameArr[$brand['uid']]['nick'] ?? '';//用户昵称
            $brand['avatar'] = $nickNameArr[$brand['uid']]['avatar'] ?? '';//用户图像
        }
        return $brandList;
    }

    /**
     * @param array $uidArr
     * @return array
     * 获取品牌身份的子身份信息 (批量)
     * @throws \Exception
     */
    public static function getBrandInfoBatch(array $uidArr = []): array
    {
        if (!$uidArr) {
            return [];
        }
        // 用户身份品牌，区分子身份
        $brandAccountMap = BrandAccount::getAllByUids($uidArr);
        $brandAccountMap = array_column($brandAccountMap, null, 'uid');

        //获取品牌信息
        $brandInfos = mBrand::selectNormalBrandsByUid($uidArr);
        $brandInfoMap = array_column($brandInfos, null, 'uid');
        $result = [];
        foreach ($uidArr as $uid) {
            if (isset($brandAccountMap[$uid])) {
                $brandAccount = $brandAccountMap[$uid];
                $res = [
                    'uid' => $uid,
                    'brand_id' => $brandInfoMap[$uid]['id'],
                    'logo' => isset($brandInfoMap[$uid]['logo']) ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ,
                        $brandInfoMap[$uid]['logo'],
                        ImgUrl::IMAGE_SIZE_SQ_PHONE) : self::BRAND_DEFAULT_LOGO,
                    'name' => $brandInfoMap[$uid]['brand_name'],
                    // 品牌类型, 分为品牌和店铺
                    'type' => $brandAccount['type'] ? (int)$brandAccount['type'] : 1,
                    'brand_type' => (int)$brandInfoMap[$uid]['brand_type'],
                    'slogan' => $brandInfoMap[$uid]['discription'] ?? '',
                    'descrip' => $brandInfoMap[$uid]['detail'] ?? '品牌还在酝酿怎么向住友介绍自己',
                    'nick' => (string)$brandAccount['nick'],
                    'letter_time' => $brandAccount['letter_time'] ?? '',
                    'letter_status' => (int)$brandAccount['letter_status'],
                    'letter_expired' => $brandAccount['descrip'],
                    'card_image' => isset($brandInfoMap[$uid]['card_image']) ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ,
                        $brandInfoMap[$uid]['card_image'],
                        ImgUrl::IMAGE_SIZE_SQ_PHONE) : '',
                ];
            } else {
                $res = [
                    'uid' => $uid,
                    'brand_id' => 0,
                    'logo' => '',
                    'name' => '',
                    'type' => 1,
                    'brand_type' => mBrand::BRAND_TYPE_EXPIRE,
                    'slogan' => '',
                    'descrip' => '',
                    'nick' => '',
                    'letter_time' => '',
                    'letter_status' => self::BRAND_ACCOUNT_EXPIRE,
                    'letter_expired' => '',
                    'card_image' => '',
                ];
            }
            $result[] = $res;
        }
        return $result;
    }

    /**
     * 获取品牌主页店铺信息
     * @param $brand_id
     * @return array
     * @throws \JsonException
     */
    public static function getIsMainShopByBrandId($brand_id)
    {
        $brand_shop_info = BrandAccount::getIsMainShopByBrandId($brand_id) ?: [];

        if (!$brand_shop_info) {
            return [];
        }
        $opacity = '80';
        $color = '#FD3C00';
        $icon = '';
        $open_app_link = '';
        $h5_link = '';
        // 1淘宝；2天猫；3京东；4其他
        switch ($brand_shop_info['type']) {
            case Wiki::CHANNEL_TYPE_TAOBAO:
            case Wiki::CHANNEL_TYPE_TMALL:
                $color = '#FD3C00';
                $icon = 'https://img.haohaozhu.cn/Op-imageShow/b07f5302c02c07B00qra1az?iv=1';
                if ($brand_shop_info['url']) {
                    $tbUrlRes = BizUrl::getTbUrl($brand_shop_info['url']);
                    $h5_link = $tbUrlRes['h5_link'];
                    $open_app_link = $tbUrlRes['open_app_link'];
                }
                break;
            case Wiki::CHANNEL_TYPE_JD:
                $color = '#FF1600';
                $icon = 'https://img.haohaozhu.cn/Op-imageShow/52413302c02c09X00qra19o?iv=1';
                if ($brand_shop_info['shop_id'] > 0) {
                    $jdUrlRes = BizUrl::getJdShopUrl($brand_shop_info['shop_id']);
                    $h5_link = $jdUrlRes['h5_link'];
                    $open_app_link = $jdUrlRes['open_app_link'];
                }
                break;
        }
        $brand_shop_info['name'] = '去店铺';
        $brand_shop_info['opacity'] = $opacity;
        $brand_shop_info['icon'] = $icon;
        $brand_shop_info['color'] = $color;
        $brand_shop_info['open_app_link'] = $open_app_link;
        $brand_shop_info['url'] = $h5_link ? LinkFormat::encryptionLink($h5_link) : '';
        return $brand_shop_info;
    }

    public static function getBrandUserInfos($brandIds, $hasCounter = false, $hasBrandResumeInfo = false, $hasFollowStatus = false)
    {
        $list = [];
        $brandList = $brandIds ? self::getBrandInfosCache($brandIds) : [];
        if ($brandList) {
            $uids = array_column($brandList, 'uid');
            $active_uid = $hasFollowStatus ? HhzClient::getUid() : 0;
            $userInfos = User::getBatchBasicUserInfo($uids, $active_uid);
            $userInfos = array_column($userInfos, null, 'uid');
            $extendInfos = MemberExtendInfo::getInfos($uids);
            if ($hasCounter) {
                $userCounterList = UserCounter::getMultiByUids($uids);
            }
            if ($hasBrandResumeInfo) {
                $resumeInfos = BrandResumeInfo::getResumeInfo($brandIds);
                $resumeInfos = $resumeInfos[0];
            }
            foreach ($brandIds as $brandId) {
                $brandInfo = $brandList[$brandId] ?? [];
                if ($brandInfo) {
                    $uid = $brandInfo['uid'];
                    $userInfo = $userInfos[$uid] ?? [];
                    $extendInfo = $extendInfos[$uid] ?? [];
                    $coverImg = empty($extendInfo['cover_img']) ? User::getUserDefaultImg($uid) :
                        ImgUrl::getUrl(ImgUrl::APPTYPE_APP, $extendInfo['cover_img'],
                            ImgUrl::IMAGE_SIZE_ORI_NPHONE);
                    $defaultLogo = $userInfo ? $userInfo['avatar'] : self::BRAND_DEFAULT_LOGO;
                    $logo = $brandInfo["logo"] ? ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $brandInfo["logo"],
                        ImgUrl::IMAGE_SIZE_SQ_PHONE) : $defaultLogo;
                    $item = [
                        'user_info' => [
                            'uid' => (int)$userInfo['uid'],
                            'nick' => $userInfo['nick'],
                            'type' => (int)$userInfo['type'],
                            'avatar' => $userInfo['avatar'],
                            'small_avatar' => $userInfo['avatar'],
                            'big_avatar' => $userInfo['avatar'],
                            'cover_img' => $coverImg,
                            'is_follow' => $userInfo['is_follow'],
                            'is_follow_new' => $userInfo['is_follow_new'],
                            'brand' => [
                                'brand_id' => $brandId,
                                'uid' => $uid,
                                'logo' => $logo,
                                'name' => $brandInfo['brand_name']
                            ]
                        ]
                    ];
                    if ($hasCounter) {
                        $item['counter'] = $userCounterList[$uid] ?? [];
                    }
                    if ($hasBrandResumeInfo) {
                        $item['resume_info'] = $resumeInfos[$brandId] ?? [];
                    }
                    $list[$brandId] = $item;
                }
            }
        }
        return $list;
    }

}
